package web

import (
	"context"
	"fmt"
	"github.com/gin-gonic/gin"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"io/ioutil"
	"net/http"
	"time"
)

func GetCourseDetail(c *gin.Context) {
	//获取参数
	id := c.Param("id")
	name := c.Query("name")
	fmt.Println(id, name)
	c.JSON(http.StatusOK, gin.H{
		"id":   id,
		"name": name,
	})
}

func GetCourseVideo(c *gin.Context) {

}

func AddCourse(c *gin.Context) {

}

func PublishCourse(c *gin.Context) {

}

func UploadCourse(c *gin.Context) {
	// 设置 MongoDB客户端
	client, err := mongo.NewClient(options.Client().ApplyURI("mongodb://username:password@localhost:27017"))
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()
	err = client.Connect(ctx)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
	imagesCollection := client.Database("test_db").Collection("images")
	// 单文件上传
	file, err := c.FormFile("file")
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	fileData, err := file.Open()
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
	defer fileData.Close()
	// 读取文件数据
	fileBytes, err := ioutil.ReadAll(fileData)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
	// 插入到数据库
	_, err = imagesCollection.InsertOne(ctx, bson.M{
		"file_name": file.Filename,
		"file_data": fileBytes,
	})
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"file_name": file.Filename,
	})
	// 多文件上传
	form, err := c.MultipartForm()
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	files := form.File["files"]
	for _, f := range files {
		f, err := f.Open()
		if err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		}
		defer f.Close()
		// 读取文件数据
		fileBytes, err := ioutil.ReadAll(fileData)
		if err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		}
		// 插入到数据库中
		_, err = imagesCollection.InsertOne(ctx, bson.M{
			"file_name": file.Filename,
			"file_data": fileBytes,
		})
		if err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		}
	}

	c.JSON(http.StatusOK, gin.H{
		"files": files,
	})
}
